package br.com.dao;

import br.com.excecoes.DAOException;
import br.com.modelo.Cliente;
import br.com.persistence.util.ExceptionsType;
import br.com.persistencia.DaoGenericImpl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Gernan
 */
public class ClienteDaoImpl extends DaoGenericImpl<Cliente> implements ClienteDao {

    public Cliente getPorId(Long id) throws DAOException {
        Criteria criteria = this.getCriteria();
        Cliente cliente = null;
        try {
            criteria.add(Restrictions.eq("id", id));
            cliente = (Cliente) criteria.uniqueResult();
        } catch (Exception e) {
            throw new DAOException(ExceptionsType.getMessage(ExceptionsType.READ_ERROR), e.getCause());
        }
        return cliente;
    }

    public Cliente getPorCpf(String cpf) throws DAOException {
        Criteria criteria = this.getCriteria();
        Cliente cliente = null;
        try {
            criteria.add(Restrictions.eq("cpf", cpf));
            cliente = (Cliente) criteria.uniqueResult();
        } catch (Exception e) {
            throw new DAOException(ExceptionsType.getMessage(ExceptionsType.READ_ERROR), e.getCause());
        }
        return cliente;
    }
    
    public List<Cliente> buscar(String busca) throws DAOException {
        Criteria criteria = this.getCriteria();
        List<Cliente> clientes  = null;
        try {
            Disjunction disjunction = Restrictions.disjunction();
            disjunction.add(Restrictions.like("nome", "%" + busca + "%"));
            disjunction.add(Restrictions.like("cpf", "%" + busca + "%"));
            disjunction.add(Restrictions.like("email", "%" + busca + "%"));
            criteria.add(disjunction);
            clientes = (List<Cliente>) criteria.list();
        } catch (Exception e) {
            throw new DAOException(ExceptionsType.getMessage(ExceptionsType.READ_ERROR), e.getCause());
        }
        return clientes;
    }
    
    public List<Cliente> getTodos() throws DAOException {
        Criteria criteria = this.getCriteria();
        List<Cliente> clientes  = null;
        try {
            criteria.addOrder(Order.asc("nome"));
            clientes = (List<Cliente>) criteria.list();
        } catch (Exception e) {
            throw new DAOException(ExceptionsType.getMessage(ExceptionsType.READ_ERROR), e.getCause());
        }
        return clientes;
    }
}